package cn.craftyun.serverlist.utils;

import cn.craftyun.serverlist.entity.RecaptchaResponse;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * Recaptcha工具
 */
public class RecaptchaUtils {
    private static final String SECRET = "6Ld4wYscAAAAAOyn6-KWOZ91ptO9iBMy1VgfbD-u";

    /**
     * 校验验证码
     *
     * @param response   客户端返回的参数
     * @param remoteAddr 客户端IP
     * @return 校验结果
     */
    public static RecaptchaResponse checkResponse(String response, String remoteAddr) {
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        MultiValueMap<String, String> reqParam = new LinkedMultiValueMap<>();
        reqParam.add("secret", SECRET);
        reqParam.add("response", response);
        reqParam.add("remoteip", remoteAddr);
        ResponseEntity<RecaptchaResponse> checkResponse = restTemplate.postForEntity("https://recaptcha.net/recaptcha/api/siteverify",
                new HttpEntity<>(reqParam, headers), RecaptchaResponse.class);
        return checkResponse.getBody();
    }
}
